import {
  getV90motorByPage,
  addV90motor,
  delV90motor,
  updateV90motor,
} from '@/services/drivepara/v90motor';

import {
  getS210motorByPage,
  addS210motor,
  delS210motor,
  updateS210motor,
} from '@/services/drivepara/s210motor';

import { EditableFormInstance, ModalForm, PageContainer, PageHeaderWrapper, ProCard, ProCardTabsProps, ProColumns, ProTable } from "@ant-design/pro-components"
import { Children, ReactText, useEffect, useRef, useState } from 'react';
import { Button, Select, Tag, message } from 'antd';
import ProList from '@ant-design/pro-list';
import { PlusOutlined } from '@ant-design/icons';
import G120Content from '@/components/DriveParaCalc/G120Content';
import { addG120motor, delG120motor, getG120motorByPage, updateG120motor, uploadG120MotorExcel } from '@/services/drivepara/g120motor';
import G120Common from '@/components/DriveParaCalc/G120Common';
import UploadFileSave from '@/components/UploadExcelSave';
import styles from './motorParaLib.less'

const MotorParaLib: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const editorFormRef = useRef<EditableFormInstance<DataSourceType>>();
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<ReactText[]>([]);
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: ReactText[]) => setSelectedRowKeys(keys),
  };
  const [g120Visible, setG120Visible] = useState(false);
  const driveRef = useRef(null);
  const [values, setValues] = useState({});
  const [motorCreate, setMotorCreate] = useState<Boolean>(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>([]);
  const [uploadG120Vis, setUploadG120Vis] = useState(false);
  const [hideG120Operation, setHideG120Operation] = useState(false);
  const uploadRef = useRef(null);
  const formData = new FormData();

  const voltageTypeMap = new Map([
    [0, '230/400V Δ/Y'],
    [1, '400/690V Δ/Y'],
  ]);

  const onG120Finish = async () => { 
    try {
      const result = driveRef.current.getFieldsValue();
      console.log(result, "---result---");
      if (motorCreate) {
        result.id = (Math.random() * 1000000).toFixed(0);
        setDataSource([...dataSource, result]);
        await addG120motor(result);
        message.success('添加成功');
      } else {
        console.log(result, "---modifyResult---");
        if (result.id !== null && result.id !== undefined) {
          for (let i = 0; i < dataSource.length; i++) {
            if (dataSource[i].id === result.id) {
              Object.assign(dataSource[i], result);
            }
          }
          
          setDataSource(dataSource);
          await updateG120motor(result);
          message.success('更新成功');
        }
      }
      actionRef.current?.reload();
      setG120Visible(false);
    } catch{}
  };

  useEffect(() => {
    (async () => {
    })();
  }, []);


  const v90Columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '电机订货号', //表头显示的名称

      dataIndex: 'motorOrderNum', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '电机ID', //表头显示的名称
      search: false,
      dataIndex: 'motorId', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 100,
    },

    {
      title: '额定电流(A)', //表头显示的名称
      search: false,
      dataIndex: 'ratedCurrent', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
    },

    {
      title: '额定扭矩(Nm)', //表头显示的名称
      search: false,
      dataIndex: 'ratedTorque', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
    },
    {
      title: '额定功率(KW)', //表头显示的名称
      search: false,
      dataIndex: 'ratedPower', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
    },
    {
      title: '编码器', //表头显示的名称
      search: false,
      dataIndex: 'ecoderType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'select',
      width: 200,
      valueEnum: {
        0: { text: '单圈绝对值编码器' },
        1: { text: '多圈绝对值编码器' },
        2: { text: '增量编码器' },
      },
      renderFormItem: (_, config, data) => {
        // 这里返回的值与Protable的render返回的值差不多,能获取到index,row,data 只是这里是获取对象组,外面会在包一层
        // console.log(config, '--');
        // 这个事v90

        return (
          <Select
            style={{ width: 120 }}
            disabled={config.record.motorOrderNum !== '第三方'}
            allowClear
            options={[
              {
                value: 0,
                label: '单圈绝对编码器',
              },
              {
                value: 1,
                label: '多圈绝对编码器',
              },
              {
                value: 2,
                label: '增量式编码器',
              },
            ]}
          />
        );
      },
    },
    {
      title: '抱闸', //表头显示的名称
      search: false,
      dataIndex: 'brake',
      valueType: 'select',
      width: 150,
      valueEnum: {
        0: { text: '不带抱闸' },
        1: { text: '带抱闸' },
      },
      renderFormItem: (_, config, data) => {
        // 这里返回的值与Protable的render返回的值差不多,能获取到index,row,data 只是这里是获取对象组,外面会在包一层
        // console.log(config, '--');
        // 这个事v90

        return (
          <Select
            style={{ width: 120 }}
            allowClear
            disabled={config.record.motorOrderNum !== '第三方'}
            options={[
              {
                value: 0,
                label: '不带抱闸',
              },
              {
                value: 1,
                label: '带抱闸',
              },
            ]}
          />
        );
      },
    },
    {
      title: '额定速度(rpm)', //表头显示的名称
      search: false,
      dataIndex: 'ratedSpeed',
      width: 120,
    },
    {
      title: '额定电压(V)', //表头显示的名称
      search: false,
      dataIndex: 'ratedVoltage', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
    },
    {
      title: '电机惯量(kgm2)', //表头显示的名称
      search: false,
      dataIndex: 'motorInertia',
      width: 120,
    },

  ];

  const s210Columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },

    {
      title: '电机订货号', //表头显示的名称

      dataIndex: 'motorOrderNum', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '额定扭矩(Nm)', //表头显示的名称
      search: false,
      dataIndex: 'ratedTorque', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },
    {
      title: '额定功率(KW)', //表头显示的名称
      search: false,
      dataIndex: 'ratedPower', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },
    {
      title: '编码器', //表头显示的名称
      search: false,
      dataIndex: 'ecoderType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'select',
      width: 220,
      valueEnum: {
        0: { text: '单圈绝对值编码器' },
        1: { text: '多圈绝对值编码器' },
        2: { text: '增量编码器' },
      },
      renderFormItem: (_, config, data) => {
        // 这里返回的值与Protable的render返回的值差不多,能获取到index,row,data 只是这里是获取对象组,外面会在包一层
        // console.log(config, '--');
        // 这个事v90

        return (
          <Select
            style={{ width: 120 }}
            disabled={config.record.motorOrderNum !== '第三方'}
            allowClear
            options={[
              {
                value: 0,
                label: '单圈绝对编码器',
              },
              {
                value: 1,
                label: '多圈绝对编码器',
              },
              {
                value: 2,
                label: '增量式编码器',
              },
            ]}
          />
        );
      },
    },
    {
      title: '抱闸', //表头显示的名称
      search: false,
      dataIndex: 'brake',
      valueType: 'select',
      width: 160,
      valueEnum: {
        0: { text: '不带抱闸' },
        1: { text: '带抱闸' },
      },
      renderFormItem: (_, config, data) => {
        // 这里返回的值与Protable的render返回的值差不多,能获取到index,row,data 只是这里是获取对象组,外面会在包一层
        // console.log(config, '--');
        // 这个事v90

        return (
          <Select
            style={{ width: 120 }}
            allowClear
            disabled={config.record.motorOrderNum !== '第三方'}
            options={[
              {
                value: 0,
                label: '不带抱闸',
              },
              {
                value: 1,
                label: '带抱闸',
              },
            ]}
          />
        );
      },
    },
    {
      title: '额定速度(rpm)', //表头显示的名称
      search: false,
      dataIndex: 'ratedSpeed',
      width: 150,
    },
    {
      title: '额定电压(V)', //表头显示的名称
      search: false,
      dataIndex: 'ratedVoltage', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },
    {
      title: '电机惯量(kgm2)', //表头显示的名称
      search: false,
      dataIndex: 'motorInertia',
      width: 150,
    },

  ];

  const g120Columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
      align: 'center',
      fixed: 'left',
    },
    {
      title: '电机厂家',
      // search: false,
      dataIndex: 'motorManufacturer',
      width: 60,
      align: 'center',
      fixed: 'left',
    },
    {
      title: '电机订货号',
      // search: false,
      dataIndex: 'motorOrderNum',
      width: 100,
      align: 'center',
      fixed: 'left',
    },
    {
      title: '电压类型',
      width: 80,
      search: false,
      align: 'center',
      key: 'voltageType',
      dataIndex: 'voltageType',
      valueType: 'select',
      valueEnum: {
        0: { text: '230/400V Δ/Y', status: 'Default' },
        1: {
          text: '400/690V Δ/Y',
          status: 'success',
        },
      },
    },
    {
      title: '电机代码选择 P301',
      search: false,
      align: 'center',
      dataIndex: 'motorId',
      width: 60,
    },
    {
      title: '额定电压 P304 [V]',
      search: false,
      dataIndex: 'ratedVoltage',
      width: 60,
      align: 'center',
    },
    {
      title: '额定电流 P305 [A]',
      search: false,
      dataIndex: 'ratedCurrent',
      width: 60,
      align: 'center',
    },
    {
      title: '额定功率 P307 [kW]',
      search: false,
      dataIndex: 'ratedPower',
      width: 60,
      align: 'center',
    },
    {
      title: '额定功率因数 P308',
      search: false,
      dataIndex: 'ratedPowerCoeff',
      width: 60,
      align: 'center',
    },
    {
      title: '额定频率 P310 [Hz]',
      search: false,
      dataIndex: 'ratedFrequency',
      width: 60,
      align: 'center',
    },
    {
      title: '额定速度 P311 [rpm]',
      search: false,
      dataIndex: 'ratedSpeed',
      width: 60,
      align: 'center',
    },
    {
      title: '额定转矩 P312 [Nm]',
      search: false,
      dataIndex: 'ratedTorque',
      width: 60,
      align: 'center',
    },
    {
      title: '连接类型 P133.0',
      width: 80,
      search: false,
      align: 'center',
      key: 'connectionType',
      dataIndex: 'connectionType',
      valueType: 'select',
      valueEnum: {
        0: { text: 'Y', status: 'Default' },
        1: {
          text: 'Δ',
          status: 'success',
        },
      },
    },
    {
      title: '87Hz运行选择 P133.1',
      width: 80,
      search: false,
      align: 'center',
      key: 'is87Hz',
      dataIndex: 'is87Hz',
      valueType: 'select',
      valueEnum: {
        0: { text: '50Hz', status: 'Default' },
        1: {
          text: '87Hz',
          status: 'success',
        },
      },
    },

    {
      title: "motorData[1] P341 [kg·m²]",
      search: false,
      dataIndex: 'motorData1',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[2] P344 [kg]",
      search: false,
      dataIndex: 'motorData2',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[3] P320",
      search: false,
      dataIndex: 'motorData3',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[4] P350",
      search: false,
      dataIndex: 'motorData4',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[5] P354",
      search: false,
      dataIndex: 'motorData5',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[6] P356",
      search: false,
      dataIndex: 'motorData6',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[7] P358",
      search: false,
      dataIndex: 'motorData7',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[8] P360",
      search: false,
      dataIndex: 'motorData8',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[9] P1825",
      search: false,
      dataIndex: 'motorData9',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[10] P1828",
      search: false,
      dataIndex: 'motorData10',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[11] P1829",
      search: false,
      dataIndex: 'motorData11',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[12] P1830",
      search: false,
      dataIndex: 'motorData12',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[13]",
      search: false,
      dataIndex: 'motorData13',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[14]",
      search: false,
      dataIndex: 'motorData14',
      width: 60,
      align: 'center',
    },
    {
      title: "motorData[15]",
      search: false,
      dataIndex: 'motorData15',
      width: 60,
      align: 'center',
    },
    {
      title: "操作",
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 90,
      hideInTable: hideG120Operation,
      render: (text, row, _, action) => [
        <a
          href={row.html_url}
          target="_blank"
          rel="noopener noreferrer"
          key="modify"
          onClick={async () => {
            console.log(row, "---row---");
            setMotorCreate(false);
            setG120Visible(true);
            setValues({ ...row });
          }}
        >
          编辑
        </a>,
        <a
          href={row.html_url}
          target="_blank"
          rel="noopener noreferrer"
          key="copy"
          onClick={async () => {
            let addone = {};
            dataSource
              .filter((item) => item.id == row.id)
              .map((item) => {
                addone = { ...item };
              });
            addone.id = (Math.random() * 1000000).toFixed(0);  
            setDataSource([...dataSource, addone]);
            delete addone.identification;
            await addG120motor(addone);
            actionRef.current.reload();
          }}
        >
          复制
        </a>,
        <a
          href={row.html_url}
          target="_blank"
          rel="noopener noreferrer"
          key="delete"
          onClick={async () => {
            setDataSource(dataSource.filter((item) => item.id !== row.id));
            await delG120motor(row);
            actionRef.current.reload();
          }}
        >
          删除
        </a>,
      ]
    }

  ];

  const [tabLabel, setTabLabel] = useState([]);

  const [tabPosition, setTabPosition] = useState<ProCardTabsProps['tabPosition']>('left');

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProCard
        style={{ maxWidth: '100%', height: '100%' }}
        tabs={{
          tabPosition,
          items: [
            {
              key: 'tab1',
              label: 'V90',
              children: 
                <ProTable
                  headerTitle="V90电机参数表"
                  className={styles.proTableSearch}
                  actionRef={actionRef}
                  rowKey="id"
                  formRef={editorFormRef}
                  scroll={{ x: 1500, y: 500 }}
                  columns={v90Columns}
                  columnsState={{
                    persistenceKey: 'pro-table-singe-demos',
                    persistenceType: 'localStorage',
                    onChange(value) {
                      console.log('value: ', value);
                    },
        
                  }}
                  search={{
                    labelWidth: 150,
                    span: 6,
                  }}
                  options={{
                    setting: {
                      listsHeight: 400,
                    },
                  }}
                  dateFormatter="string"
                  request={async (params = {}, sort, filter) => {
                    console.log(params, sort, filter);
                    const result = await getV90motorByPage(params);
                    return {
                      data: result.data.content,
                      total: result.data.totalElements,
                      success: result.success,
                    };
                    // return  await new Promise({data:[{loginName:}], total:10, success: 0})
                    // return {data:[], total:10, success: 0}
                  }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
                  rowSelection={{}}
                  pagination={{
                    showSizeChanger: true,
                  }}
                ></ProTable>
              ,
            },
            {
              key: 'tab2',
              label: 'S210',
              children: 
                <ProTable
                  headerTitle="S210电机参数表"
                  className={styles.proTableSearch}
                  actionRef={actionRef}
                  rowKey="id"
                  formRef={editorFormRef}
                  scroll={{ x: 1500, y: 500 }}
                  columns={s210Columns}
                  columnsState={{
                    persistenceKey: 'pro-table-singe-demos',
                    persistenceType: 'localStorage',
                    onChange(value) {
                      console.log('value: ', value);
                    },
        
                  }}
                  search={{
                    labelWidth: 150,
                    span: 6,
                  }}
                  options={{
                    setting: {
                      listsHeight: 400,
                    },
                  }}
                  dateFormatter="string"
                  request={async (params = {}, sort, filter) => {
                    console.log(params, sort, filter);
                    const result = await getS210motorByPage(params);
                    return {
                      data: result.data.content,
                      total: result.data.totalElements,
                      success: result.success,
                    };
                    // return  await new Promise({data:[{loginName:}], total:10, success: 0})
                    // return {data:[], total:10, success: 0}
                  }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
                  rowSelection={{}}
                  pagination={{
                    showSizeChanger: true,
                  }}
                ></ProTable>,
            },
            {
              key: 'tab3',
              label: 'G120',
              children:
                <ProTable
                  className={styles.proTableSearch}
                  headerTitle="G120电机参数表"
                  actionRef={actionRef}
                  formRef={editorFormRef}
                  columns={g120Columns}
                  scroll={{ x: 3800, y: 500 }}
                  rowKey="id"
                  // columnsState={{
                  //   persistenceKey: 'pro-table-singe-demos',
                  //   persistenceType: 'localStorage',
                  //   onChange(value) {
                  //     console.log('value: ', value);
                  //   },
        
                  // }}
                  search={{
                    labelWidth: 150,
                    span: 6,
                  }}
                  options={{
                    setting: {
                      listsHeight: 400,
                    },
                  }}
                  dateFormatter="string"
                  toolBarRender={(action, { selectedRows, selectedRowKeys }) => [
                    <Button
                      key="button"
                      icon={<PlusOutlined />}
                      type="primary"
                      onClick={() => {
                        setUploadG120Vis(true);
                        setHideG120Operation(true);
                      }}
                    >
                      导入
                    </Button>,
                    <Button
                      key="button"
                      icon={<PlusOutlined />}
                      type="primary"
                      onClick={() => {
                        setValues({});
                        setG120Visible(true);
                        setMotorCreate(true);
                      }}
                    >
                      新建
                    </Button>,
                  ]}
                  revalidateOnFocus={false}
                  request={async (params = {}, sort, filter) => {
                    console.log(params, sort, filter);
                    const result = await getG120motorByPage(params);
                    console.log(result, '---result---');
                    setDataSource(result.data.content);
                    return {
                      data: result.data.content,
                      total: result.data.totalElements,
                      success: result.success,
                    };
                  }}
                  
                  rowSelection={{}}
                  pagination={{
                    showSizeChanger: true,
                  }}

                ></ProTable>
            },
          ],
        }}
      >
      </ProCard>
      <G120Common
        visible={g120Visible}
        title='G120电机参数预览'
        disabled={false}
        values={values}
        ref={driveRef}
        initialValues={values}
        onCancel={() => {
          setG120Visible(false);
        }}
        onOk={onG120Finish}
      />
      <UploadFileSave
        visible={uploadG120Vis}
        title='G120电机上传参数预览'
        tableHeader={g120Columns}
        errorStatus={false}
        ref={uploadRef}
        onChange={(file) => {
          formData.append('file', file);
        }}
        onCheck={() => { }}
        onCancel={() => {
          setUploadG120Vis(false);
          setHideG120Operation(false);
        }}
        onOk={async (tables, tableHeader) => {
          console.log(tables, "---tables---");
          
          console.log(uploadRef.current.fileList, '文件测试---');
          const result = await uploadG120MotorExcel(formData);
          
          console.log(result, "---formData---");
          if (result != undefined && result != null) {
            setDataSource([...dataSource, result.data]);
          }
          // setDataSourceTwo(tables);
          actionRef.current.reload();
          setUploadG120Vis(false);
          setHideG120Operation(false);
        }}
      />
    </PageHeaderWrapper>
  );


};

export default MotorParaLib;